<?php

namespace app\api\controller;

use app\api\model\Order as OrderModel;
use app\common\controller\Api;
use app\api\model\User as UserModel;

/**
 * 订单接口
 */
class Order extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['index'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function index()
    {
        // 获取用户id
        $user_id = $this->auth->__get('id');
        // 获取用户模型
        $user = UserModel::get($user_id);
        // 获取用户对应订单数据
        $orders = $user->orders;
        if (!empty($orders)) {
            // 返回数组
            $result = [];
            foreach ($orders as $key => $order) {
                $result[] = [
                    'orderId' => $order->id,
                    'orderImgUrl' => $order->image,
                    'orderTitle' => $order->count,
                    'isCommented' => $order->is_commented,
                    'orderAmount' => $order->amount,
                ];
            }
            $this->success('查询成功', $result);
        }

        $this->error('没有订单数据');
    }

    /**
     * 用户评论详情
     *
     * @return void
     */
    public function detailComment()
    {
        if ($this->request->isGet()) {
            $data = $this->request->param();

            // 获取用户id
            $user_id = $this->auth->__get('id');
            // 获取订单
            $order = OrderModel::get($data['orderID']);

            if (!$order) {
                $this->error('未找到订单');
            }

            if($order->user->id != $user_id){
                $this->error('订单不属于你');
            }

            $comments = $order->comments;
            if (empty($comments)) {
               $this->success('查询成功');
            }
            $ret = [];
            foreach ($comments as $key => $comment) {
                $ret[] = [
                    'comment' => $comment->content,
                    'rate' => $comment->rate,
                    'commentImgs' => $comment->comment_imgs,
                    'orderID' => $order->id,
                ];
            }

            $this->success('查询成功',[
                'rows' => $ret
            ]);
        }
    }
}
